package cn.wyu.web;

import cn.wyu.dao.UserDao;
import cn.wyu.dao.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/register.do")
public class registerServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //处理中文乱码问题
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //2.获取数据
        //2.1获取用户填写验证码
        String verifycode = request.getParameter("verifycode");

        //3.验证码校验
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
        session.removeAttribute("CHECKCODE_SERVER");//确保验证码一次性
        if(!checkcode_server.equalsIgnoreCase(verifycode)){
            //验证码不正确
            //提示信息
            request.setAttribute("register_msg","验证码错误！");
            //跳转登录页面
            request.getRequestDispatcher("/register.jsp").forward(request,response);

            return;
        }

        //接收用户注册的信息
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");
        String password2 = request.getParameter("password2");
        String Name = request.getParameter("Name");
        UserDao userDao = new UserDaoImpl();
        userDao.register(loginName,password);


        //重定向到登录页面
        response.sendRedirect("login.do");


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request, response);
    }
}
